// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const dayjs = require('dayjs');
const uuid = require('uuid');
async function _setIntervalHandle(param = {}) {
	const dbJQL = uniCloud.databaseForJQL({
		...this
	});
	const todayEndTime = dayjs().startOf('day').add(1, 'days').subtract(1, 'milliseconds').valueOf();
	const todayStartTime = dayjs().startOf('day').valueOf();
	const todayNowTime = dayjs().valueOf();
	console.log('endTime', todayEndTime)
	console.log('startTime', todayNowTime)
	// 查询出结束在当前时间内的任务
	const TodayTaskListRes = await dbJQL.collection('task_list').where(
		`"((endTime <= ${todayNowTime} && endTime > ${todayStartTime}) || startTime <= ${todayNowTime} ) && delFlag == '0' && taskRepeat == '1'"`
	).get()
	console.log('查到的数据创建在今日的，和在今日内要结束的', TodayTaskListRes)
	const {
		data
	} = TodayTaskListRes
	const len = data.length
	let changeFlag = false
	for (let i = 0; i < len; i++) {
		const item = data[i]
		const {
			endTime,
			startTime,
			status
		} = item
		// 从未开始变成进行中
		if (startTime <= todayNowTime && status == 0) {
			item.status = '1'
			changeFlag = true
		}
		// 如果全部子任务没有完成，变成 未完成任务
		if (endTime <= todayNowTime && status < 2) {
			item.status = '3'
			changeFlag = true
		}
	}
	if (!changeFlag) return
	console.log('发生改变需要更新数据库')
	const dbTaskList = dbJQL.collection('task_list')
	for (let i = 0; i < len; i++) {
		const item = data[i]
		dbTaskList.where(`"_id=='${item._id}'"`).update({
			...item
		})
	}
}
module.exports = {
	_before: function() { // 通用预处理器

	},
	_timing: function(param) {
		console.log('this', this)
		return _setIntervalHandle(param)
	},
	_setIntervalHandle,
}